<template>
  <section class="app-inner">
    <el-card class="header-card">
      <el-form :inline="true" ref="deviceForm" :model="queryParams">
        <el-form-item>
          <el-select
          @change="changeType"
          v-model="queryParams.typeId"
          placeholder="全部类型">
            <el-option
              v-for="item in deviceTypeList"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            ></el-option>
            </el-select>
        </el-form-item>

        <el-form-item>
          <el-select
          v-model="queryParams.deviceState"
          placeholder="全部状态">
            <el-option
              v-for="item in deviceStatusList"
              :key="item.val"
              :label="item.name"
              :value="item.val"
            ></el-option>
            </el-select>
        </el-form-item>

        <el-form-item>
          <el-input clearable placeholder="请输入设备名称" v-model="queryParams.deviceName"></el-input>
        </el-form-item>

        <el-form-item class="searchBtn">
          <el-button v-if="checkAuthority('/select')" type="primary" @click="searchQuery">查询</el-button>
        </el-form-item>
        <el-form-item v-if="control === '灯光控制' && ListOrCard === 'list'">
          <el-radio-group v-model="lamplightSwitch" @change="handleLamplightSwitch">
            <el-radio-button :label="1002" >全开</el-radio-button>
            <el-radio-button :label="1003">全关</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="control === '空调' && checkAuthority('/season/switch')">
          <el-switch
            v-model="seasonStatus"
            active-color="#13ce66"
            active-text="冬季"
            inactive-text="夏季"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item v-if="control === '空调' && ListOrCard === 'list'">
          <el-button type="primary" disabled @click="handleBatchTemp">集中控温</el-button>
        </el-form-item>

        <el-radio-group v-model="ListOrCard" class="searchRight" style="margin-bottom: 20px;">
          <el-radio-button label="list">列表</el-radio-button>
          <el-radio-button label="card">卡片</el-radio-button>
        </el-radio-group>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane v-for="item in tabsList"
        :key="item.typeId" :label="item.typeName"
        :id="item.typeId" :name="item.typeId"></el-tab-pane>
        <!-- <el-tab-pane label="校园环境监测" name="environment"></el-tab-pane>
        <el-tab-pane label="校园安全监测" name="security"></el-tab-pane>
        <el-tab-pane label="校园管理监测" name="management"></el-tab-pane> -->
      </el-tabs>

      <!-- 列表 -->
      <div v-if="ListOrCard === 'list'">

        <el-table :data="tableData" style="width: 100%" ref="tableRef" @selection-change="handleSelectionChange">
          <el-table-column v-if="control === '灯光控制' || control === '空调'" type="selection" width="55" />
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="deviceNumber" show-overflow-tooltip label="设备编号"></el-table-column>
          <el-table-column prop="deviceName" label="设备名称" width="120"></el-table-column>
          <el-table-column prop="address" show-overflow-tooltip label="地点"></el-table-column>
          <el-table-column prop="deviceState" label="设备状态">
            <template slot-scope="scope">
              {{deviceStatusEnum[scope.row.deviceState]}}
            </template>
          </el-table-column>

          <el-table-column
            v-for="(item,index) in tableHeaders"
            :prop="item.paramName"
            :key="index"
            :label="item.paramMemo"
            width="140"
          >
          <template slot-scope="{ row, column }">
            <!-- 校园管理监测 tab 灯光控制下拉 light: 亮度，colorTemperature: 色温-->
            <el-input-number
              :disabled="!row.tempStatus"
              v-if="item.paramName === 'light' && control === '灯光控制'"
              v-model="row.light"
              @change="handleStep('light', row)"
              :step="25"
              size="mini"
              :min="0"
              :max="100"
            ></el-input-number>
            <el-input-number
              :disabled="!row.tempStatus"
              v-else-if="item.paramName === 'colorTemperature' && control === '灯光控制'"
              v-model="row.colorTemperature"
              @change="handleStep('colorTemperature', row)"
              :step="25"
              size="mini"
              :min="0"
              :max="100"
            ></el-input-number>
            <span
              v-else
              :style="formatter(row, column)[0] ? {color: 'red'} : {}"
            >
              {{ formatter(row, column)[1] }}
            </span>
          </template>
          </el-table-column>
          <!-- 空调 - 温度控制 -->
          <el-table-column prop="tempCtrl" :label="control === '空调' ? '温度控制' : ''" :width="control === '空调' ? 280 : 0">
            <template slot-scope="{ row }" v-if="control === '空调'">
              <el-switch
                disabled
                v-model="row.tempCtrl"
                @change="handleTemCtrl(row, 'temp')"
                active-color="#13ce66"
                active-text="制热"
                inactive-text="制冷"
                inactive-color="#ff4949">
              </el-switch>
              <el-input-number
                size="mini"
                disabled
                style="margin-left: 10px"
                v-model="row.num"
                controls-position="right"
                @change="handleTemCtrl(row, 'tempValue')"
                :min="row.tempCtrl ? 23 : 18"
                :max="row.tempCtrl ? 28 : 25"
              ></el-input-number> ℃
            </template>
          </el-table-column>
          <el-table-column prop="tempStatus" v-if="hasControl" :label="control" width="140">
            <template slot-scope="scope">
              <section v-if="typeName === '空气质量'">
                <!-- 空气质量多个设备 -->
                <div class="switch-wrap" v-for="item in scope.row.controlDeviceList" :key="item.deviceNumber">
                  <el-tooltip effect="dark" :content="item.deviceName" placement="top">
                    <div class="ellipsis" v-if="scope.row.controlDeviceList && scope.row.controlDeviceList.length > 1">{{ item.deviceName }}</div>
                  </el-tooltip>
                  <el-switch
                    @click.native.stop="changeSwitch(item)"
                    v-model="item.tempStatus"
                    active-color="#13ce66"
                    active-text="开"
                    inactive-text="关"
                    inactive-color="#ff4949">
                  </el-switch>
                </div>
              </section>
              <el-switch
                v-else
                @click.native.stop="changeSwitch(scope.row)"
                v-model="scope.row.tempStatus"
                active-color="#13ce66"
                active-text="开"
                inactive-text="关"
                inactive-color="#ff4949">
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="240" v-if="isShowHistory">
            <template slot-scope="scope">
              <template v-if="control === '烟感'">
                <el-button type="text" @click="handleSilencer(scope.row, '持续消音')">持续消音</el-button>
                <el-button type="text" @click="handleSilencer(scope.row, '单次消音')">单次消音</el-button>
              </template>
              <el-button type="text" @click="handleRead(scope.row)">历史数据</el-button>
              <!-- <el-button type="text" @click="handleRemove(scope.row)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 卡片 -->
      <section class="wrapper" v-if="ListOrCard === 'card'">
        <el-row class="itemRow" :gutter="20" v-if="tableData && tableData.length">
          <el-col :span="8" v-for="(item,index) in tableData" :key="index">
            <div class="grid-content bg-purple" @click="detailFn($event,item)" :id="index">
              <el-card class="box-card cardBorder">
                <img src="~@/assets/images/login2/clip.svg" class="svg"/>
                <!-- 上部分 -->
                <div class="cardTop">
                  <div class="device">
                    <div class="deviceWrapper">
                      <p class="deviceItem">
                        <span :style="{ background: setColor()}" class="circle1"> </span>
                        <span style="margin-left: 10px;">设备{{deviceStatusEnum[item.deviceState]}}</span>
                      </p>
                    </div>
                    <div class="deviceWrapper">
                      <p class="deviceItem" style="margin-top: 5px;">
                        <span class="circle2"> </span>
                        <el-tooltip class="item" effect="dark" :content="item.deviceName" placement="right">
                          <span class="deviceNameCss" style="margin-left: 10px;">{{item.deviceName}}</span>
                        </el-tooltip>
                      </p>
                      <div class="deviceSwitch" v-if="hasControl">
                          <section v-if="typeName === '空气质量'">
                            <!-- 空气质量多个设备 -->
                            <div class="switch-wrap" v-for="device in item.controlDeviceList" :key="device.deviceNumber">
                              <el-tooltip effect="dark" :content="item.deviceName" placement="top">
                                <div class="ellipsis" v-if="item.controlDeviceList && item.controlDeviceList.length > 1">{{ device.deviceName }}</div>
                              </el-tooltip>
                              <el-switch
                                @click.native.stop="changeSwitch(device)"
                                v-model="device.tempStatus"
                                active-color="#13ce66"
                                active-text="开"
                                inactive-text="关"
                                inactive-color="#ff4949">
                              </el-switch>
                            </div>
                          </section>
                          <el-switch
                            v-else
                            @click.native.stop="changeSwitch(item)"
                            v-model="item.tempStatus"
                            active-color="#13ce66"
                            active-text="开"
                            inactive-text="关"
                            inactive-color="#ff4949">
                          </el-switch>
                      </div>
                    </div>
                  </div>

                  <div class="img" :style="control === '灯光控制' || control === '空调' ? {flex: 1} : {}">
                    <div class="imgWrapper" :style="{ color: setColor()}">
                      <span :class="['iconfont', setIconName(), control === '灯光控制' ? 'w60' : 'w80']"></span>
                    </div>
                    <div>
                      <div class="title" style="text-align: center;">{{item.deviceName}}</div>
                      <div class="address" style="text-align: center;">{{item.address}}</div>
                    </div>
                  </div>
                  <!-- 灯光控制 - 亮度/色温 -->
                  <div v-if="control === '灯光控制'" class="light-ctrl">
                    <div class="light-ctrl-wrap">
                      <div class="light-ctrl-item">
                        <span>亮度</span>
                        <el-input-number :disabled="!item.tempStatus" v-model="item.light" @click.stop.native="()=>{}" @change="handleStep('light', item)" :step="25" size="mini" :min="0" :max="100"></el-input-number>
                      </div>
                      <div class="light-ctrl-item">
                        <span>色温</span>
                        <el-input-number :disabled="!item.tempStatus" v-model="item.colorTemperature" @click.stop.native="()=>{}" @change="handleStep('colorTemperature', item)" :step="25" size="mini" :min="0" :max="100"></el-input-number>
                      </div>
                    </div>
                  </div>
                  <div v-if="control === '空调'" class="temp-ctrl">
                    <div class="temp-ctrl-wrap">
                      <div class="temp-ctrl-item">
                        <el-switch
                          disabled
                          @click.stop.native="()=>{}"
                          @change="handleTemCtrl(item, 'temp')"
                          v-model="item.tempCtrl"
                          active-color="#13ce66"
                          active-text="制热"
                          inactive-text="制冷"
                          inactive-color="#ff4949">
                        </el-switch>
                      </div>
                      <div class="temp-ctrl-item">
                        温度
                        <el-input-number
                          size="mini"
                          disabled
                          @click.stop.native="()=>{}"
                          v-model="item.num"
                          controls-position="right"
                          @change="handleTemCtrl(item, 'tempValue')"
                          :min="item.tempCtrl ? 23 : 18"
                          :max="item.tempCtrl ? 28 : 25"
                        ></el-input-number> ℃
                      </div>
                    </div>
                  </div>
                </div>
                <!-- 分割线 -->
                <p class="lineCss"></p>
                <!-- 下部分 -->
                <div class="cardBottom">
                  <div class="itemAttr" v-for="(val,key,index) in item.content" :key="index">
                    <i class="el-icon-location items itemI" style="margin-right: 4px;"></i>
                    <!-- <img class="greenItem" src="~@/assets/images/login2/CO2.svg"/> -->
                    <p class="itemText">&nbsp;
                    {{ attrEnum[key]}} : <span :style="listFormatter(val, key)[0] ? { color: 'red'} : {}">{{ listFormatter(val, key)[1] }}</span>
                    </p>
                  </div>
                  <!--<div class="itemAttr">
                    <img class="blueItem" src="~@/assets/images/login2/formaldehyde.svg"/>
                    <i class="el-icon-location items itemII"></i>
                    <p class="itemText">
                    甲醛：100
                    </p>
                  </div>
                  <div class="itemAttr">
                    <img class="originItem" src="~@/assets/images/login2/PM2.5.svg"/>
                    <i class="el-icon-location items itemIII"></i>
                    <p class="itemText">
                    PM2.5:100
                    </p>
                  </div>-->
                </div>
              </el-card>
            </div>
          </el-col>
        </el-row>
        <el-empty v-else description="暂无数据"></el-empty>
      </section>

      <el-pagination
        style="text-align: right"
        class="paginationCss"
        v-if="tableData.length > 0"
        layout="total, prev, pager, next"
        @current-change="changePage"
        :current-page="queryParams.current"
        :page-size="queryParams.pageSize"
        :total="totalCount"
      ></el-pagination>
    </el-card>

    <!-- <el-card class="table-card" >
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="校园环境监测" name="environment"></el-tab-pane>
        <el-tab-pane label="校园安全监测" name="security"></el-tab-pane>
        <el-tab-pane label="校园管理监测" name="management"></el-tab-pane>
      </el-tabs>
    </el-card> -->
    <!-- 集中控温弹窗 -->
    <el-dialog
      :visible.sync="temperatureDialogVisible"
      width="400px"
      :show-close="false"
      center
    >
      <section class="temperature">
        <el-switch
          @click.stop.native="()=>{}"
          @change="handleTemperatureCtrl('temp')"
          v-model="temperatureCtrl"
          active-color="#13ce66"
          active-text="制热"
          inactive-text="制冷"
          inactive-color="#ff4949">
        </el-switch>
        <div class="temperature-num">
          温度
          <el-input-number
            size="mini"
            @click.stop.native="()=>{}"
            v-model="temperatureNum"
            controls-position="right"
            @change="handleTemperatureCtrl('tempValue')"
            :min="temperatureCtrl ? 23 : 18"
            :max="temperatureCtrl ? 28 : 25"
          ></el-input-number> ℃
        </div>
      </section>
      <span slot="footer" class="dialog-footer">
        <el-button @click="temperatureDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleBatchTemperature">确 定</el-button>
      </span>
    </el-dialog>
    <!--  v-if="visibleHistory" -->
    <history-data :tableHeaders="tableHeaders" :typeName="typeName" :autoDialogWidth='autoDialogWidth' ref="historyModel" v-if="visibleHistory"></history-data>
  </section>
</template>

<script>
import {
  getDeviceDataStatisticsList,
  getDeviceOneCatalog,
  getDeviceOneCatalog2,
  getControlMethodNameForTheDeviceType,
  getDeviceColumn,
  controlDevice,
  lamplightBeachDeviceControl,
  temperatureBatchControl
} from './js/deviceStatistics.js'
import historyData from './components/historyData.vue'
import { indicator, iconList, unitList } from './js/indicatorConstant'
import { checkAuthority } from '@/utils/btnPermission' // 页面按钮权限
import '@/styles/iconfont/iconfont.css'
export default {
  name: 'statistics',
  components: {
    historyData
  },
  computed: {
    isShowHistory () {
      return (
        this.iconName !== '智能井盖' &&
        this.iconName !== '温感' &&
        this.iconName !== '燃气' &&
        this.iconName !== '智能垃圾桶'
      )
    }
  },
  data () {
    return {
      activeName: '',
      queryParams: {
        current: 1,
        pageSize: 10,
        typeId: '',
        deviceName: '',
        deviceState: 0
      },
      typeName: '',
      autoDialogWidth: '',
      tabsList: [],
      totalCount: 1,
      ListOrCard: 'list',
      deviceTypeList: [],
      colorIndex: 0,
      deviceStatusList: [ // 1 告警 2 正常 3 离线
        {
          name: '正常',
          val: 0
        },
        {
          name: '告警',
          val: 1
        },
        {
          name: '离线',
          val: 2
        },
        {
          name: '损坏',
          val: 3
        }
      ],
      deviceStatusEnum: {
        0: '正常',
        1: '告警',
        2: '离线',
        3: '损坏'
      },
      attrEnum: {},
      // tableHeaders: ['PM2.5', '甲醛', '二氧化碳'],
      tableHeaders: [],
      hasControl: 0,
      control: '',
      controlRes: '',
      current: {},
      deviceControlMethod: '',
      tableData: [],
      visibleHistory: false,
      iconName: '',
      lamplightSwitch: '',
      checkSelection: [],
      temperatureDialogVisible: false,
      temperatureCtrl: true,
      temperatureNum: 23, // 23: 制热最低温 18：制冷最低温
      seasonStatus: false // 夏季false、冬季true
    }
  },
  async mounted () {
    await this.getDeviceOneCatalog()
    await this.searchQuery()
  },
  methods: {
    checkAuthority,
    // tab页切换
    handleClick (e) {
      // 切换后自动获取该类型下二级目录列表
      this.getDeviceOneCatalog2(e.name)
    },
    // 搜索
    searchQuery () {
      this.queryParams.current = 1
      this.initData()
    },
    // 更改状态时要同步更改映射字段
    async changeType (val) {
      await this.getDeviceColumn(val) // 获取映射字段
      this.getControlMethodNameForTheDeviceType(val)
      this.typeName = this.deviceTypeList.find(item => item.typeId === val).typeName
      this.controlName()
      this.searchQuery() // 获取列表
    },
    // 获取一级目录
    async getDeviceOneCatalog () {
      try {
        let res = await getDeviceOneCatalog(2)
        if (res.code === 0) {
          this.tabsList = res.data
          this.activeName = this.tabsList[0].typeId // 默认选中tabs 第一个
          await this.getDeviceOneCatalog2(this.tabsList[0].typeId) // 获取第一个tabs的二级目录下拉框数据
        } else {
          this.$message.error(res.msg)
        }
      } catch (e) {
      }
    },
    // 设备二级目录获取 （类型下拉框数据）
    async getDeviceOneCatalog2 (typeId) {
      try {
        let res = await getDeviceOneCatalog2({ typeId })
        if (res.code === 0) {
          this.deviceTypeList = res.data
          this.queryParams.typeId = this.deviceTypeList[0].typeId // 默认选择第一个类型
          this.getControlMethodNameForTheDeviceType(this.queryParams.typeId)
          this.typeName = this.deviceTypeList[0].typeName
          this.controlName()
          await this.getDeviceColumn(this.queryParams.typeId)
        } else {
          this.$message.error(res.msg)
        }
      } catch (e) {}
    },
    // 获取设备反控接口方法名
    async getControlMethodNameForTheDeviceType (deviceTypeId) {
      const res = await getControlMethodNameForTheDeviceType(deviceTypeId)
      if (res.code === 0) {
        this.deviceControlMethod = res.data
      }
    },
    // 设备反控
    async controlDevice (methodName, params, type = null) {
      try {
        const res = await controlDevice(methodName, params)
        if (res.code === 0) {
          this.$message.success('操作成功！')
          if (!type) this.initData()
        } else {
          this.$message.error(res.msg)
          if (!type) this.initData()
        }
      } catch (e) {
      }
    },
    async handleLamplightSwitch () {
      // 控制灯光全开/全关
      if (!this.checkSelection?.length) {
        this.$message.warning('请先勾选！')
        this.lamplightSwitch = ''
        return false
      }
      const params = this.checkSelection.map(n => ({
        colorTemperature: n.content.colorTemperature || 0,
        light: n.content.light || 0,
        commandId:
          n.deviceName === '黑板灯' && this.lamplightSwitch === 1002
            ? 1005
            : n.deviceName === '黑板灯' && this.lamplightSwitch === 1003
              ? 1006
              : this.lamplightSwitch,
        id: n.deviceNumber
      }))
      try {
        const res = await lamplightBeachDeviceControl(params)
        if (res.code === 0) {
          this.$message.success('灯光控制成功！')
          this.initData()
        }
      } catch (e) {}
    },
    handleSelectionChange (val) {
      // 表格勾选复选框
      this.checkSelection = val
    },
    handleBatchTemp () {
      // 集中控温
      if (!this.checkSelection?.length) {
        this.$message.warning('请先勾选！')
        return false
      }
      this.temperatureDialogVisible = true
    },
    async handleBatchTemperature () {
      // 批量控温
      const params = this.checkSelection.map(n => ({
        downLinkType: 0,
        openOrOff: this.temperatureNum,
        serialNumber: n.deviceNumber,
        temperatureControlFlag: this.temperatureCtrl ? 1 : 0
      }))
      try {
        const res = await temperatureBatchControl(params)
        if (res.code === 0) {
          this.temperatureDialogVisible = false
          // 集中控温列表数据更新
          this.$refs.tableRef.clearSelection()
          this.tableData.forEach(n => {
            params.forEach(m => {
              if (m.serialNumber === n.deviceNumber) {
                n.tempCtrl = !!m.temperatureControlFlag
                n.num = m.openOrOff
              }
            })
          })
          this.$message.success('集中控温成功！')
        }
      } catch (e) {}
    },
    handleTemperatureCtrl (type) {
      // 批量修改制冷/制热、温度
      if (type === 'temp') {
        // 制冷/制热 23: 制热最低温 18：制冷最低温
        this.temperatureNum = this.temperatureCtrl ? 23 : 18
      } else if (type === 'tempValue') {
        // 温度
      }
    },
    handleStep (type, row) {
      // 灯光控制 - 亮度、色温
      const { light, colorTemperature } = row
      let params = {}
      if (type === 'light') {
        params = this.setBodyParams(row.deviceNumber, 1008, light)
      } else if (type === 'colorTemperature') {
        params = this.setBodyParams(row.deviceNumber, 1008, null, colorTemperature)
      }
      this.controlDevice(this.deviceControlMethod, params)
    },
    // 控制字段的名称
    controlName () {
      if (this.typeName.includes('空气质量')) {
        this.control = '空气净化器'
      } else {
        this.control = this.typeName
      }
      this.setIconName()
    },
    // 设置当前icon展示
    setIconName () {
      this.iconName = iconList.find(n => n.name === this.typeName)?.name
      const url = iconList.find(n => n.name === this.typeName)?.url
      return url
    },
    // 获取设备数据指标映射字段
    async getDeviceColumn (params) {
      try {
        let res = await getDeviceColumn(params)
        if (res.code === 0) {
          this.hasControl = res.data.hasControlFlag
          this.tableHeaders = res.data.deviceColumnList || []
          this.autoDialogWidth = this.tableHeaders.length
          this.tableHeaders.forEach(item => {
            this.attrEnum[item.paramName] = item.paramMemo
          })
          this.searchQuery()
        }
      } catch (e) {}
    },
    // 列表数据获取
    async initData () {
      try {
        let res = await getDeviceDataStatisticsList({
          ...this.queryParams
        })
        if (res.code === 0) {
          let tempRes = res.data.records
          tempRes.forEach(item => {
            if (item.content) {
              for (let key in item.content) {
                item[key] = item.content[key]
              }
            }
            if (item.controlDeviceState === 1) {
              item.tempStatus = true
            } else {
              item.tempStatus = false
            }
            if (this.typeName === '空气质量') {
              item.controlDeviceList.forEach(n => {
                n.tempStatus = !!n.controlDeviceState
              })
            }
            // 空调 - 温度控制 23: 制热最低温 18：制冷最低温
            if (this.control === '空调') {
              item.tempCtrl = true
              item.num = item.tempCtrl ? 23 : 18
            }
          })
          this.tableData = tempRes
          this.totalCount = res.data.total
          this.lamplightSwitch = ''
          this.colorIndex = this.queryParams.deviceState
        }
      } catch (e) {}
    },
    // 历史数据
    handleRead (row) {
      this.visibleHistory = true
      this.$nextTick(() => {
        this.$refs.historyModel.open(row)
      })
    },
    handleSilencer (row, type) {
      // 消音
      let params = {}
      if (type === '持续消音') {
        // 持续消音
        params = {
          code: '07' // 04:单次消⾳; 07:持续消⾳; 0d:单次撤防;
        }
      } else if (type === '单次消音') {
        // 单次消音
        params = {
          code: '04' // 04:单次消⾳; 07:持续消⾳; 0d:单次撤防;
        }
      }
      this.controlDevice(this.deviceControlMethod, {
        downLinkType: 0, // 下发消息类型 0 立即下发； 1 缓存下发
        serialNumber: row.deviceNumber,
        type: 82, // 消音指令82 切换工作模式84
        workMode: 0, // 工作模式 0-正常 1–静⾳报警模式; 2–持续撤防模式
        ...params
      })
    },
    formatter (row, column) {
      const [flagBad, value] = this.getFormatterData(row[column.property], column.property)
      return [flagBad, value]
    },
    listFormatter (val, key) {
      // 列表卡片超过正常指标数值变红色
      const [flagBad, value] = this.getFormatterData(val, key)
      return [flagBad, value]
    },
    getFormatterData (val, key) {
      const bad = indicator.find(n => n.indicator === key)?.bad
      const best = indicator.find(n => n.indicator === key)?.best
      let flagBad = val >= bad
      let flagGood = val >= best && val < bad
      let flagBest = val < best
      let flag = ''
      if (best) {
        flag = flagBad ? '差' : flagGood ? '良' : flagBest ? '优' : ''
      } else if (key === 'h2S_Rtd' || key === 'nh3_Rtd') {
        // 目前硫化氢和氨气才有差和正常标识
        flag = flagBad ? '差' : '正常'
      }
      const unit = unitList.find(n => n.prop === key)?.unit ?? ''
      const value = val ? `${flag} ${val} ${unit}` : ''
      return [flagBad, value]
    },
    // 翻页
    changePage (val) {
      this.queryParams.current = val
      this.initData()
    },
    handleTemCtrl (row, type) {
      // 温度控制
      let params = {}
      if (type === 'temp') {
        // 制热/制冷
        this.tableData.forEach(n => {
          n.num = (row.tempCtrl && row.deviceNumber === n.deviceNumber) ? 23 : 18
        })
        params = {
          temperatureControlFlag: row.tempCtrl ? 1 : 0, // 1: 制热 0：制冷
          openOrOff: row.num ?? row.tempCtrl ? 23 : 18
        }
      } else if (type === 'tempValue') {
        // 温度值
        params = {
          temperatureControlFlag: row.tempCtrl ? 1 : 0, // 1: 制热 0：制冷
          openOrOff: row.num
        }
      }
      this.controlDevice(this.deviceControlMethod, {
        downLinkType: 0, // 0: 立即下发 1: 暂缓下发
        serialNumber: row.deviceNumber, // 设备序列号
        ...params
      }, 'temp')
    },
    changeSwitch (row) {
      this.current = row
      let params = {}
      if (this.typeName.includes('空气质量')) {
        params = {
          downLinkType: 0, // 0: 立即下发 1: 暂缓下发
          openOrOff: row.tempStatus ? 0 : 1, // 0: 开 1: 关
          serialNumber: row.deviceNumber // 设备序列号
        }
      } else if (this.typeName.includes('空调')) {
        // openOrOff：夏季模式（seasonStatus：false） 1 开 / 2关;冬季模式（seasonStatus：true） 3 开 / 4关
        const openOrOff =
          this.seasonStatus && row.tempStatus
            ? 3 : this.seasonStatus && !row.tempStatus ? 4
              : !this.seasonStatus && row.tempStatus ? 1 : 2
        params = {
          downLinkType: 0, // 0: 立即下发 1: 暂缓下发
          openOrOff, // 1: 开 2: 关
          serialNumber: row.deviceNumber, // 设备序列号
          eqptId: row.eqptId
        }
      } else if (this.typeName.includes('空气净化器')) {
        params = {
          downLinkType: 0, // 0: 立即下发 1: 暂缓下发
          openOrOff: row.tempStatus ? 1 : 2, // 1: 开 2: 关
          serialNumber: row.deviceNumber, // 设备序列号
          eqptId: row.eqptId
        }
      } else if (this.typeName.includes('烟感')) {
        params = {
          code: '04', // 04:单次消⾳; 07:持续消⾳; 0d:单次撤防;
          downLinkType: 0, // 下发消息类型 0 立即下发； 1 缓存下发
          serialNumber: row.deviceNumber,
          type: 82, // 消音指令82 切换工作模式84
          workMode: 0 // 工作模式 0-正常 1–静⾳报警模式; 2–持续撤防模式
        }
      } else if (this.typeName.includes('灯光控制')) {
        let commandId = null
        if (row.tempStatus && row.deviceName === '黑板灯') {
          commandId = 1005 // 黑板灯开
        } else if (!row.tempStatus && row.deviceName === '黑板灯') {
          commandId = 1006 // 黑板灯关
        } else if (row.tempStatus) {
          commandId = 1002 // 开
        } else {
          commandId = 1003 // 关
        }
        params = this.setBodyParams(row.deviceNumber, commandId)
      }
      this.controlDevice(this.deviceControlMethod, params)
    },
    detailFn ($event, item) {
      if (this.isShowHistory) this.visibleHistory = true
      this.$nextTick(() => {
        this.$refs.historyModel.open(item)
      })
    },
    setColor () {
      return ['#92D21B', '#E86548', '#9B9B9B', '#FFA800'][this.colorIndex ?? 0] || '#92D21B'
    },
    setBodyParams (deviceNumber, commandId, light = null, colorTemperature = null) {
      /*
      * commandId: 1002单个教室灯开灯， 1003单个教室灯关灯， 1008教室单个灯亮度和色温调节
      * @return params {}
      */
      return {
        downLinkType: 0, // 下发消息类型 0 立即下发； 1 缓存下发
        serialNumber: deviceNumber,
        beanName: '',
        information: {
          commandId, // 1002开灯，1003关灯
          // id: '010100124b001b62a406',
          id: deviceNumber,
          light,
          colorTemperature
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.switch-wrap {
  display: flex;
  align-items: center;
}
.ellipsis {
  margin-right: 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 1;
}
.temperature {
  display: flex;
  flex-direction: column;
  align-items: center;
  &-num {
    margin-top: 20px;
  }
}
.tabs {
  display: inline-block;
}
.btns {
  border: 1px solid rgba(0, 0, 0, 0.1);
  height: 42px;
  display: flex;
  justify-content:space-between;
  align-items: flex-start;
  width: 161px;
  // border-radius:20%;
  // float: right;
}
.spanI {
  // display: inline-block;
  // width: 1px;
  height: 38px;
  border-left: 1px solid rgba(0, 0, 0, 0.1);
}
.listOrCard {
  display: inline-block;
  text-align: center;
  cursor: pointer;
  width: 79px;
}
.activeBackground {
  background-color:#D4FFF1;
}
/deep/ .el-button {
  border-radius: 0;
}
/deep/ .el-form-item__content {
  width: 100%;
}
.bg-purple {
  width: 100%;
  background-color: rgba(204, 204, 204, 0.2);
  margin-bottom: 20px;
  position: relative;
  overflow: hidden;
}
.cardBorder {
  border-radius: 10%;
  margin: 10px;
  ::v-deep .el-card__body {
    padding: 20px;
  }
}
/deep/ .el-card {
  border-radius: 12px !important;
}
.svg {
  position: absolute;
  right: 16px;
  top: 4px;
  width: 30px;
  height: 30px;
}
.cardTop {
  width: 100%;
  display:flex;
  height: 150px;
}
.device {
  margin-left: -24px;
  display:flex;
  flex-direction:column;
}
.deviceWrapper {
  padding: 0 10px;
  width: 100%;
  background-color: rgba(204, 204, 204, 0.2);
  border-radius: 10px;
  margin-bottom: 5px;
}
.light-ctrl {
  margin-right: -24px;
  &-wrap {
    text-align: right;
    .light-ctrl-item {
      margin-bottom: 5px;
      background-color: rgba(204, 204, 204, 0.2);
      padding-left: 10px;
      border-radius: 10px;
      & > .el-input-number {
        margin-left: 5px;
      }
    }
  }
}
.temp-ctrl {
  margin-right: -20px;
  &-wrap {
    text-align: right;
    .temp-ctrl-item {
      margin-bottom: 5px;
      background-color: rgba(204, 204, 204, 0.2);
      padding-left: 10px;
      border-radius: 10px;
    }
  }
}
.deviceItem {
  height: 26px;
  line-height: 26px;
  font-size:12px;
  position: relative;
}
.circle1 {
  display: inline-block;
  position: absolute;
  top:40%;
  border-radius: 50%;
  width: 5px;
  height: 5px;
  background-color: #FF8F1F;
}
.deviceSwitch {
  text-align:center;
  margin-bottom: 3px;
}
.deviceNameCss{
  white-space: nowrap;  /*强制span不换行*/
  display: inline-block;  /*将span当做块级元素对待*/
  width: 90%;  /*限制宽度*/
  overflow: hidden;  /*超出宽度部分隐藏*/
  text-overflow: ellipsis;  /*超出部分以点号代替*/
  line-height: 0.9;  /*数字与之前的文字对齐*/
}
.img {
  margin: 0 10px;
  display: inline-block;
  .imgWrapper {
    text-align: center;
    color: #92D21B;
  }
}
.w60 {
  font-size: 60px;
}
.w80 {
  font-size: 80px;
}
.lineCss {
  margin-top: 20px;
  border-bottom: 1px solid rgba(204, 204, 204, 0.2);
  width: 100%;
}
.greenItem {
  background-color: green;
}
.blueItem {
  background-color:blue;
}
.items {
  width: 15px;
  height: 15px;
  text-align: center;
  line-height: 15px;
  font-size: 14px;
  color: #ffffff;
}
.cardBottom {
  margin-top: 10px;
  display: flex;
  justify-content:space-between;
  align-items: flex-start;
  min-height: 60px;
  flex-wrap: wrap;
  .itemAttr {
    width: 50%;
  }
}
.itemI {
  background-color:green;
}
.itemII {
  background-color:blue;
}
.itemIII {
  background-color:orange;
}
.itemText {
  display: inline-block;
}
.el-input-number {
  width: 100px;
}
</style>

<style scoped>
.circle1,.circle2{
  display: inline-block;
  position: absolute;
  top:40%;
  border-radius: 50%;
  width: 5px;
  height: 5px;
  background-color: #FF8F1F;
}
.circle2 {
  background-color: #00B578;
}
</style>
